import { Component, OnInit, Inject } from '@angular/core';
import {
    FormBuilder,
    FormGroup,
    Validators,
    FormControl
} from '@angular/forms';
import {
    HttpClient,
    HttpHeaderResponse,
    HttpHeaders,
    HttpParams,
    HttpHandler
} from '@angular/common/http';
import { Router } from '@angular/router';
import { User } from '../entity/User';
import { NzMessageService } from 'ng-zorro-antd';

@Component({
    selector: 'app-register',
    templateUrl: './register.component.html',
    styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
    validateForm: FormGroup;
    validateFormTeacher: FormGroup;
    saveUrl = '/api/User/insert';
    sexs: string[];

    // 提交表单时验证
    _submitForm() {
        for (const i in this.validateForm.controls) {
            if (i) {
                this.validateForm.controls[i].markAsDirty();
            }
        }
        if (this.validateForm.status !== 'VALID') {
            return;
        }
        this.validateForm.value.userType = '学生';
        this.RegisterUser(this.validateForm.value);
    }
    _submitFormTeacher() {
        for (const i in this.validateFormTeacher.controls) {
            if (i) {
                this.validateFormTeacher.controls[i].markAsDirty();
            }
        }
        if (this.validateFormTeacher.status !== 'VALID') {
            return;
        }
        this.validateFormTeacher.value.userType = '老师';
        this.RegisterUser(this.validateFormTeacher.value);
    }

    // 往后台请求，注册用户
    RegisterUser(user: User) {
        this.http
            .post(this.saveUrl, JSON.stringify(user), {
                headers: new HttpHeaders({
                    'Content-type': 'application/json'
                })
            })
            .subscribe(response => {
                response = response as boolean;
                if (response) {
                    this.router.navigate(['/content/home']);
                } else {
                    this.message.error('邮箱已经存在');
                }
            });
    }

    
    constructor(
        private fb: FormBuilder,
        private http: HttpClient,
        private router: Router,
        private message: NzMessageService,
    ) {
        this.sexs = ['男', '女'];
    }

    updateConfirmValidator() {
        /** wait for refresh value */
        setTimeout(_ => {
            this.validateForm.controls[
                'checkPassword'
            ].updateValueAndValidity();
        });
    }
    updateTeacherConfirmValidator() {
        /** wait for refresh value */
        setTimeout(_ => {
            this.validateFormTeacher.controls[
                'checkPassword'
            ].updateValueAndValidity();
        });
    }

    // 验证密码是否一致
    confirmationValidator = (
        control: FormControl
    ): { [s: string]: boolean } => {
        if (!control.value) {
            return { required: true };
        } else if (
            control.value !== this.validateForm.controls['password'].value
        ) {
            return { confirm: true, error: true };
        }
    };

    confirmationTeacherValidator = (
        control: FormControl
    ): { [s: string]: boolean } => {
        if (!control.value) {
            return { required: true };
        } else if (
            control.value !==
            this.validateFormTeacher.controls['password'].value
        ) {
            return { confirm: true, error: true };
        }
    };

    getCaptcha(e: MouseEvent) {
        e.preventDefault();
    }

    // 初始化
    ngOnInit() {
        // 定义验证规则
        this.validateForm = this.fb.group({
            email: [null, [Validators.email]],
            password: [null, [Validators.required]],
            checkPassword: [
                null,
                [Validators.required, this.confirmationValidator]
            ],
            name: [null, [Validators.required]],
            phoneNumberPrefix: ['+86'],
            sex: [null],
            phoneNumber: [null, [Validators.required]],
            agree: [true]
        });

        this.validateFormTeacher = this.fb.group({
            email: [null, [Validators.email]],
            password: [null, [Validators.required]],
            sex: [null],
            checkPassword: [
                null,
                [Validators.required, this.confirmationTeacherValidator]
            ],
            name: [null, [Validators.required]],
            phoneNumberPrefix: ['+86'],
            phoneNumber: [null, [Validators.required]],
            agree: [true]
        });
    }

    getFormControl(name) {
        return this.validateForm.controls[name];
    }

    getTeacherFormControl(name) {
        return this.validateFormTeacher.controls[name];
    }
}
